
$(() => {
    const user = JSON.parse(sessionStorage.getItem('user'))

    $('#preview').attr('src', user.avatar)
    $('#hiddenInput').val(user.avatar)
    $('#email').val(user.email)
    $('#nickName').val(user.nickName)

    //图片上传
    $('#avatar').on('change', function () {
        const formData = new FormData()
        formData.append('avatar', this.files[0])
        $.ajax({
            type: 'post',
            url: '/upload',
            data: formData,
            processData: false,
            contentType: false,
            success(res) {
                $('#preview').attr('src', res[0].avatar)
                $('#hiddenInput').val(res[0].avatar)
            }
        })
    })

    //表单提交
    $('#userForm').submit(function () {
        const formData = $(this).serialize()
        $.ajax({
            type: 'put',
            url: `/users/${user._id}`,
            data: formData,
            success(res) {
                sessionStorage.setItem('user', JSON.stringify(res))
                const user = JSON.parse(sessionStorage.getItem('user'))
                $('#avatarPreview').attr('src', user.avatar)
                $('#nickName').html(user.nickName)
            },
            error() {
                alert('修改失败!')
            }
        })

        return false
    })
})